package eu.testing.system.dao.impl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.springframework.jdbc.core.simple.ParameterizedRowMapper;
import org.springframework.jdbc.core.simple.SimpleJdbcDaoSupport;

import eu.testing.system.dao.VariantDao;
import eu.testing.system.models.Variant;

public class VariantDaoImpl extends SimpleJdbcDaoSupport implements VariantDao {

	private static final String SQL_SELECT_ALL = "SELECT * FROM variant WHERE TEST_ID =? "
			+ "AND QUESTION_ID = ?";
	private static final String SQL_DELETE = "DELETE FROM variant WHERE TEST_ID = ?";
	private static final String SQL_UPDATE = "UPDATE variant SET VALUE = ? WHERE TEST_ID = ? AND QUESTION_ID = ? AND VARIANT_ID = ?";
	private static String SQL_INSERT = "INSERT INTO variant (TEST_ID,QUESTION_ID,VARIANT_ID,TRUTH, VALUE) VALUES (?,?, ?, ?, ?)";


	@Override
	public void insertVariant(Variant variant) {
		getSimpleJdbcTemplate().update(SQL_INSERT, variant.getTestId(),
				variant.getQuestionId(), variant.getVariantId(),
				variant.isTruth(), variant.getValue());

	}

	@Override
	public void deleteVariant(int testId) {
		getJdbcTemplate().update(SQL_DELETE, testId);

	}

	@Override
	public List<Variant> getAllVariantsById(int testId, int questionId) {
		List<Variant> variants = getSimpleJdbcTemplate().query(SQL_SELECT_ALL,
				new VariantParameterizedRowMapper(), testId, questionId);

		return variants;
	}

	public class VariantParameterizedRowMapper implements
			ParameterizedRowMapper<Variant> {
		@Override
		public Variant mapRow(ResultSet rs, int rowNum) throws SQLException {
			Variant test = new Variant();
			test.setQuestionId(rs.getInt("TEST_ID"));
			test.setQuestionId(rs.getInt("QUESTION_ID"));
			test.setVariantId(rs.getInt("VARIANT_ID"));
			test.setTruth(rs.getBoolean("TRUTH"));
			test.setValue(rs.getString("VALUE"));
			return test;
		}

	}

	@Override
	public void editVariant(Variant variant) {
		getJdbcTemplate().update(SQL_UPDATE, variant.getValue(),
				variant.getTestId(), variant.getQuestionId(),
				variant.getVariantId());

	}
}
